package com.haohan.cloud.scm.wecaht.wxapp.api;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.framework.entity.BaseResp;
import com.haohan.cloud.scm.api.common.BaseApiService;
import com.haohan.cloud.scm.api.common.CommonApiConstant;
import com.haohan.cloud.scm.api.constant.ScmCommonConstant;
import com.haohan.cloud.scm.api.manage.entity.UPassport;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseEmployee;
import com.haohan.cloud.scm.api.purchase.req.PurchaseEmployeeReq;
import com.haohan.cloud.scm.api.salec.feign.StoreOrderFeignService;
import com.haohan.cloud.scm.api.salec.feign.UserFeignService;
import com.haohan.cloud.scm.api.salec.req.AfterPayUpdReq;
import com.haohan.cloud.scm.api.salec.req.StoreOrderReq;
import com.haohan.cloud.scm.api.supply.entity.Supplier;
import com.haohan.cloud.scm.api.supply.req.SupplierReq;
import com.haohan.cloud.scm.api.wechat.req.WechatAddReq;
import com.haohan.cloud.scm.api.wechat.req.WechatBindTelReq;
import com.haohan.cloud.scm.api.wechat.req.WechatLoginReq;
import com.haohan.cloud.scm.api.wechat.resp.WechatLoginResp;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.haohan.cloud.scm.wecaht.wxapp.utils.ScmWechatUtils;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.data.tenant.TenantContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @program: haohan-fresh-scm
 * @description: 基础服务API
 * @author: Simon
 * @create: 2019-07-18
 * 不验证token
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/api/wechat/wxapp")
@Api(value = "BaseApiCtrl", tags = "微信小程序基础接口服务")
public class WechatBaseApiCtrl {

    private final BaseApiService apiService;
    private final ScmWechatUtils scmWechatUtils;
    private final UserFeignService userFeignService;
    private final StoreOrderFeignService storeOrderFeignService;
    private final ScmIncrementUtil scmIncrementUtil;

    /**
     * 暂未使用 (采购员工小程序)
     *
     * @param req
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "采购部员工/供应商登录", notes = "采购部员工/供应商登录, 返回员工/供应商信息")
    R login(@Validated WechatLoginReq req) {
        WechatLoginResp resp = new WechatLoginResp();
        PurchaseEmployeeReq employeeReq = new PurchaseEmployeeReq();
        employeeReq.setPassportId(req.getUid());
        PurchaseEmployee employee = scmWechatUtils.fetchPurchaseEmployee(employeeReq);
        if (null != employee) {
            resp.copyFormPurchase(employee);
            return R.ok(resp);
        }
        // 供应商 登录
        SupplierReq supplierReq = new SupplierReq();
        supplierReq.setPassportId(req.getUid());
        Supplier supplier = scmWechatUtils.fetchSupplier(supplierReq);
        if (null != supplier) {
            resp.copyFormSupplier(supplier);
            return R.ok(resp);
        }
        return R.failed("登录失败");
    }

    /**
     * 暂未使用 (采购员工小程序)
     *
     * @param req
     * @return
     */
    @PostMapping("/bindTel")
    @ApiOperation(value = "绑定手机号", notes = "采购部员工/供应商 绑定手机号")
    R bindTel(@Validated WechatBindTelReq req) {
        String uid = req.getUid();
        String telephone = req.getTelephone();
        // 验证uid是否正确
        scmWechatUtils.queryUPassportById(uid);
        // 验证手机号是否已设置
        boolean flag = false;
        WechatLoginResp resp = new WechatLoginResp();
        // 绑定前uid
        String originalUid = "";
        // 采购部
        PurchaseEmployeeReq employeeReq = new PurchaseEmployeeReq();
        employeeReq.setTelephone(telephone);
        PurchaseEmployee employee = scmWechatUtils.fetchPurchaseEmployee(employeeReq);
        if (null != employee) {
            flag = true;
            resp.copyFormPurchase(employee);
            originalUid = employee.getPassportId();
            PurchaseEmployee update = new PurchaseEmployee();
            update.setId(employee.getId());
            update.setPassportId(uid);
            scmWechatUtils.updatePurchaseEmployee(update);
        }
        // 供应商
        if (!flag) {
            SupplierReq supplierReq = new SupplierReq();
            supplierReq.setTelephone(telephone);
            Supplier supplier = scmWechatUtils.fetchSupplier(supplierReq);
            if (null != supplier) {
                flag = true;
                resp.copyFormSupplier(supplier);
                originalUid = supplier.getPassportId();
                Supplier updateSupplier = new Supplier();
                updateSupplier.setId(supplier.getId());
                updateSupplier.setPassportId(uid);
                scmWechatUtils.updateSupplier(updateSupplier);
            }
        }
        // 通行证绑定
        if (flag) {
            // 前后通行证不一致 设置 取消以前的passport中 telephone, 当前passport中设置telephone
            if (StrUtil.isNotEmpty(originalUid) && !StrUtil.equals(originalUid, uid)) {
                UPassport origin = scmWechatUtils.queryUPassportById(originalUid);
                UPassport update = new UPassport();
                if (StrUtil.equals(origin.getTelephone(), telephone)) {
                    update.setId(originalUid);
                    update.setTelephone("");
                    scmWechatUtils.updateUPassport(update);
                }
                update.setId(uid);
                update.setTelephone(telephone);
                scmWechatUtils.updateUPassport(update);
            }
            return R.ok(resp);
        }
        return R.failed("绑定手机号失败");
    }

    /**
     * 暂未使用 (采购员工小程序)
     *
     * @param req
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "小程序用户关联", notes = "小程序用户关联upassport,返回uid")
    R add(@Validated WechatAddReq req) {
        BaseResp baseResp = apiService.call(CommonApiConstant.wechat_app_add, req);
        if (baseResp.isSuccess()) {
            return R.ok(baseResp.getExt());
        }
        return R.failed(baseResp.getMsg());
    }

    /**
     * 暂未使用 (商城小程序)
     *
     * @param req
     * @return
     */
    @PostMapping("/orderPayUpdBalance")
    @ApiOperation(value = "支付后根据状态更新余额")
    R orderPayUpdBalance(@RequestBody @Validated AfterPayUpdReq req) {
        return userFeignService.orderPayUpdBalance(req, SecurityConstants.FROM_IN);
    }

    /**
     * 订单支付后更新订单状态 (商城小程序使用)
     *
     * @param req
     * @return
     */
    @PostMapping("/afterPayOrderUpdOrderStatus")
    @ApiOperation(value = "订单支付后更新订单状态")
    R<Boolean> afterPayOrderUpdOrderStatus(@RequestBody @Validated AfterPayUpdReq req) {
        StoreOrderReq query = new StoreOrderReq();
        query.setOrderId(req.getOrderId());
        return storeOrderFeignService.afterPayOrderUpdOrderStatus(query, SecurityConstants.FROM_IN);
    }

    /**
     * 是否关闭支付功能 (小程序使用)
     *
     * @param appId 小程序id
     * @return true 关闭支付功能
     */
    @GetMapping("/payFlag")
    @ApiOperation(value = "开始或关闭支付功能")
    R<Boolean> payFlag(String appId) {
        // 多租户单独控制小程序开关
        Integer tenantId = TenantContextHolder.getTenantId();
        if (tenantId == null) {
            tenantId = 1;
        }
        // 按appId单独控制
        String infix = StrUtil.isEmpty(appId) ? StrUtil.COLON  : StrUtil.COLON + appId + StrUtil.COLON;
        // 缓存中值为true时 开启支付
        boolean flag = Boolean.parseBoolean(scmIncrementUtil.fetchValue(tenantId.toString() + infix + ScmCommonConstant.PAY_FLAG));
        return RUtil.success(!flag);
    }
}
